/**
 * Created by PhpStorm.
 * User: bsc
 * Date: 2020-11-03
 * Time: 21:34
 */

const Koa = require("koa")
const KoaBody = require("koa-body")
const KoaStaticCache = require("koa-static-cache")
const KoaJwt = require("koa-jwt")
const Jwt = require("jsonwebtoken")
const Router = require("@koa/router")
const Mysql2 = require("mysql2")


const app = new Koa();
const router = new Router();
const connection = Mysql2.createConnection({
  user: "root",
  password: "bsc123321",
  database: "kkb",
})

const secret = 'kkb';
app.use(KoaJwt({
  secret
}).unless({
  path: [/^\/(public|static|login)/]
}));

// 静态资源代理
app.use(KoaStaticCache("./public", {
  prefix: "/public",
  gzip: true,
  dynamic: true,
}))

router.get("/getPhotos", async ctx => {
  let imgs = await query('select * from `photos` where `user_id`=?', [ctx.state.user.id])
  ctx.body = {
    msg: '成功',
    state: 1,
    data: imgs
  }
})

router.post("/upload", KoaBody({
  multipart: true,
  formidable: {
    uploadDir: './public/upload',
    keepExtensions: true,
  }
}), async ctx => {

  // 获取文件对象
  let {
    attachment
  } = ctx.request.files;
  let index = attachment.path.lastIndexOf('/')
  let fileName = attachment.path.substring(index + 1)
  let fileSize = attachment.size;
  let fileType = attachment.type;
  let user = ctx.state.user;
  let res = await query('insert into `photos` (`filename`,`size`,`type`,`user_id`) values (?,?,?,?)', [fileName, fileSize, fileType, user.id])

  if (res.affectedRows) {
    ctx.body = {
      msg: "上传成功",
      state: 1,
      data: {
        name: fileName
      }
    }
  } else {
    ctx.body = {
      msg: "上传失败",
      state: 0
    }
  }
})

router.post("/login", KoaBody(), async ctx => {
  let {
    username,
    password
  } = ctx.request.body;
  let res = await query('select * from `users` where `username`=? and `password`=?', [username, password])
  if (res.length) {

    const token = Jwt.sign({
      username: res[0].username,
      id: res[0].id,
    }, secret, {
      expiresIn: "2h"
    });

    ctx.set("Authorization", token)

    ctx.body = {
      msg: "登录成功",
      state: 1,
      data: {
        token: token
      }
    }
  } else {
    ctx.body = {
      msg: "用户名或密码错误",
      state: 0,
      data: []
    }
  }
})

app.use(router.routes())




app.listen(8888, () => {
  console.log("启动成功: http://localhost:8888")
})

function query(sql, data) {
  return new Promise((resolve, reject) => {
    connection.query(sql, data, (err, ...data) => {
      if (err) {
        reject(err)
      } else {
        resolve(...data)
      }
    })

  })
}